package de.sono.radio.fragments;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import de.sono.radio.R;
import de.sono.radio.list.RadioStation;
import de.sono.radio.parser.HTMLParser;

public class RadioStreamer extends ListFragment implements
		LoaderManager.LoaderCallbacks<List<RadioStation>> {
	
	public static final String RADIO_STATION_URL = "station_url";
	public static final String RADIO_LOADER_ID = "station_loader_id";
	private final String LOG_TAG = RadioStreamer.class.getSimpleName();

	private OnRadioStationSelectListener mActivity;
	private List<RadioStation> stations;
	private StationAdapter adapter;
	private int loaderId;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try{	
			mActivity = (OnRadioStationSelectListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() + " must implement OnArticleSelectedListener");
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		setEmptyText("Sender werden geladen!");

		adapter = new StationAdapter(getActivity());

		setListAdapter(adapter);

		ListView lv = getListView();
		lv.setDividerHeight(2);

		setListShown(false);

		loaderId = getArguments().getInt(RADIO_LOADER_ID);
		getLoaderManager().initLoader(loaderId, getArguments(), this);

	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		RadioStation station = stations.get(position);
		mActivity.startStreamingService(station);

	}

	public void reloadData() {
		Toast.makeText(getActivity(), "reload not yet implemented",
				Toast.LENGTH_LONG).show();
	}

	@Override
	public Loader<List<RadioStation>> onCreateLoader(int arg0, Bundle arg1) {
		Log.d(LOG_TAG, "Task gestartet");

		String url = arg1.getString(RADIO_STATION_URL);

		return new RadioLoader(getActivity(), url);

	}

	@Override
	public void onLoadFinished(Loader<List<RadioStation>> pRadioLoader,
			List<RadioStation> pRadioList) {
		// Populate list with our static array of titles.
		setListShownNoAnimation(true);
		stations = pRadioList;
		adapter.setData(stations);
		if (stations == null) {
			setEmptyText("Es konnten keine Sender geladen werden!");
		}
	}

	@Override
	public void onLoaderReset(Loader<List<RadioStation>> arg0) {
		// TODO Auto-generated method stub
		adapter.setData(null);
	}

	public interface OnRadioStationSelectListener {
		public void startStreamingService(RadioStation pStation);
	}

	private class StationAdapter extends ArrayAdapter<RadioStation> {


		public StationAdapter(Context context) {
			super(context, R.layout.station_info);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getActivity()
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.station_info, parent, false);
			}

			RadioStation a = getItem(position);
			if (a != null) {
				TextView station = (TextView) v.findViewById(R.id.station_name);
				TextView info = (TextView) v.findViewById(R.id.station_info);

				ImageView iv = (ImageView) v.findViewById(R.id.station_img);
				byte[] img = a.getImg();
				Bitmap bmp = BitmapFactory.decodeByteArray(img, 0, img.length);
				iv.setImageBitmap(bmp);

				station.setText(String.valueOf(a.getName()));
				info.setText(a.getInfo());

			}
			return v;
		}

		public void setData(List<RadioStation> mList) {
			clear();
			if (mList != null) {
				for (RadioStation s : mList) {
					add(s);
				}
			}
		}

	}

	private static class RadioLoader extends
			AsyncTaskLoader<List<RadioStation>> {

		private String LOG_TAG = RadioLoader.class.getSimpleName();
		private String mUrl;
		private List<RadioStation> mStations;
		
		public RadioLoader(Context context, String pUrl) {
			super(context);
			mUrl = pUrl;
		}
		
		@Override
		public List<RadioStation> loadInBackground() {
			try {
				HTMLParser parser = new HTMLParser();
				List<RadioStation> stations = parser.getStations(mUrl);
				Log.d(LOG_TAG, "Stations gefunden");
				return stations;

			} catch (Exception e) {
				Log.d(LOG_TAG, e.toString());
				return null;
			}
		}

		@Override
		public void deliverResult(List<RadioStation> data) {
			mStations = data;
			super.deliverResult(data);
		}

		@Override
		protected void onReset() {
			onStartLoading();
			mStations = null;
		}

		@Override
		protected void onStartLoading() {
			// if (mStations != null) {
			// deliverResult(mStations);
			// } else {
				forceLoad();
			// }
		}

		@Override
		protected void onStopLoading() {
			cancelLoad();
		}

	}
}